<!--
  - Copyright (C) 2018-2022
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
	<view>
		<cu-custom :bgColor="'bg-'+theme.backgroundColor" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">{{ title }}</block>
		</cu-custom>
		<view>
			<im-connect :fixed='true'></im-connect>
		</view>
		<view class="cu-chat" id="chatlist" style="padding-bottom: 120rpx;">
			<view class="margin-top message">
				<view class="cu-item" :class="item.sendID==IMuserID?'self':''" v-for="(item,index) in chatMessageRecord"
					:key="index" :id="(item)">
					<view v-if="item.sendID!=IMuserID" class="cu-avatar round"
						:style="{backgroundImage:'url('+item.senderFaceUrl+')'}"></view>
					<view class="main">
						<!--消息类型-->
						<!--https://doc.rentsoft.cn/#/js_v2/sdk_integrate/struct?id=%e6%b6%88%e6%81%af%e7%b1%bb%e5%9e%8b      -->
						<view class="content message-bg" :class="item.sendID==IMuserID?'bg-white':''">
							<view v-if="item.contentType==110">
								<!-- 自定义的消息类型,可以根据类型分别显示不同的消息,类型可自定义 -->
								<base-message :msgBody="item.customElem?JSON.parse(item.customElem.data):''">
								</base-message>
							</view>
							<view v-else>
								<text>{{ item.content }}</text>
							</view>
						</view>
					</view>
					<view v-if="item.sendID==IMuserID" class="cu-avatar round"
						:style="{backgroundImage:'url('+item.senderFaceUrl+')'}"></view>
					<view class="date ">{{ item.sendTime | formatTimeMsg }}</view>
				</view>
			</view>
			<view v-if="topMsgContent" style="padding-bottom: 50rpx;">
				<view class="bg-white goods-bg radius padding-bottom">
					<view class="flex padding">
						<view class="cu-avatar image-box bg-white"
							:style="{'background-image':topMsgContent.imgUrl?'url('+topMsgContent.imgUrl+')':''}">
						</view>
						<view class="content flex-sub padding-left-sm text-sm margin-top-xs">
							<view class="text-lg overflow-2">{{ topMsgContent.name }}</view>
							<view class="cu-tag df bg-red radius margin-top-xs">{{ topMsgContent.type }}</view>
							<view class="margin-top-xs text-red text-xl text-bold">{{ topMsgContent.desc }}</view>
						</view>
					</view>
					<view class="cu-btn round df flex margin-top" style="width: 50%; margin: auto;" @click="sendTopMsg"
						:class="'bg-'+theme.backgroundColor">发送客服
					</view>
				</view>
			</view>
		</view>

		<view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
			<view class="action">
				<!-- <text class="cuIcon-sound text-grey"></text> -->
			</view>
			<input class="solid-bottom " :adjust-position="false" :focus="false" maxlength="300" cursor-spacing="10"
				@focus="InputFocus" @blur="InputBlur" v-model="inputMsgText"></input>
			<view class="action">
				<!-- <text class="cuIcon-emojifill text-grey"></text> -->
			</view>
			<button class="cu-btn bg-green" @click="to_send()">发送</button>
		</view>
	</view>
</template>

<script>
	/**
	 * Copyright (C) 2018-2019
	 * All rights reserved, Designed By www.joolun.com
	 * 注意：
	 * 本软件为www.joolun.com开发研制，未经购买不得使用
	 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
	 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
	 */
	/**
	 * 1.拉取聊天记录
	 * 2.如果未联网，显示本地的消息记录
	 *
	 */

	const util = require("utils/util.js");
	const app = getApp();
	import api from '@/utils/api'
	import JimUtil from '@/utils/jim-util' // IM工具库

	// 基础消息类型
	import baseMessage from '@/components/chat-message/index.vue';
	import imConnect from '@/components/chat-message/im-connect' //im连接状态

	export default {
		components: {
			baseMessage,
			imConnect
		},
		data() {
			return {
				// 本地历史消息
				chatRecordLocalSaveKey: "chat_record_" + app.globalData.tenantId + '_', // key由 当前用户id和客服id组成，保证一对一的数据
				CustomBar: this.CustomBar,
				theme: app.globalData.theme, //全局颜色变量
				title: '消息',
				chatUserId: null, //客服userId(对方IM的ID)
				chatUserinfo: {
					showName: ''
				},
				chatMessageRecord: [],
				inputMsgText: '',
				InputBottom: 0,
				topMsgContent: null, // 顶部消息的内容
				showPage: false, //是否显示页面，用于消息未读数刷新
				sendMsgSuccess: true, // 消息是否发送成功，只有发送成功才能发送下一条
				getMessageOptions: {
					userID: "", //拉取单个用户之间的聊天消息
					groupID: "", //
					startClientMsgID: "", // 起始的消息clientMsgID，第一次拉取为""
					count: 999, //拉取消息的数量
				},
				IMuserID: app.globalData.IMdata.IMuserID,
				JIMConnect: false
			};
		},
		filters: {
			formatTimeMsg(time) {
				return JimUtil.parseTimeMsg(time);
			},
		},
		onShow() {
			app.initJIM().then(res => {
				this.loadChatRecord()
				this.toBottom()
			}).catch(err => {
				this.loadLocalChatRecord()
			});
			//键盘高度监听事件
			uni.onKeyboardHeightChange(res => {
				this.InputBottom = res.height
			})
		},
		onUnload() {
			this.showPage = false
			uni.$off('JIMLogin')
			uni.$off('JIMDisconnect')
			uni.$off('JIMMsgChange')
			uni.offKeyboardHeightChange(res => {
				this.InputBottom = 0
			})
		},
		onLoad(options) {
			if (!uni.getStorageSync('user_info') || !uni.getStorageSync('user_info').id) {
				uni.reLaunch({
					url: '/pages/login/index'
				});
				return
			}
			this.chatUserId = options.chatUserId //客服userId（聊天对象ID）
			if (options.showName) {
				this.title = options.showName
			}
			//当前登录人
			this.IMuserID = JimUtil.GetIMuserID()
			this.showPage = true
			this.getMessageOptions.userID = this.chatUserId
			this.chatRecordLocalSaveKey = "chat_record_" + this.IMuserID + this.chatUserId;

			//自定义消息
			if (options.goodsSpuId) {
				this.goodsGet(options.goodsSpuId);
			} else if (options.orderInfoId) {
				this.orderGet(options.orderInfoId);
			}
			// 连接断开监听
			uni.$on('JIMDisconnect', (data) => {
				this.JIMConnect = false
				this.loadLocalChatRecord();
			})
			// 登录监听
			uni.$on('JIMLogin', (data) => {
				this.JIMConnect = true
				this.loadChatRecord()
			})
			// 收到消息监听
			uni.$on('JIMMsgChange', (data) => {
				if (this.showPage) {
					this.loadChatRecord()
				}
			})
		},
		methods: {
			sendMessage(message) {
				let that = this
				// 发送消息之前要创建消息
				let JIM = app.globalData.JIM;
				JIM.sendMessage(message).then(({
					data,
					errCode
				}) => {
					that.chatMessageRecord.push(JSON.parse(data))
					that.inputMsgText = ''
					that.toBottom()
					JimUtil.saveIMMsg(that.chatMessageRecord, this.getMessageOptions.userID)
					console.log('save local msg success');
					that.topMsgContent = null
					this.sendMsgSuccess = true
				}).catch(err => {
					if (err.errCode == 301) {
						uni.showToast({
							title: "发送消息失败，未找到客服",
							icon: "none"
						})
					} else {
						uni.showToast({
							title: "发送消息失败",
							icon: "none"
						})
					}
				});
			},
			orderGet(id) {
				let that = this;
				api.orderGet(id).then(res => {
					let orderInfo = res.data;
					let imgUrl = orderInfo.listOrderItem[0].picUrl
					this.topMsgContent = { // JLIM自定义消息内容的长度有限制，所以精简一些
						id: orderInfo.id, //ID
						imgUrl: imgUrl, //图片
						name: orderInfo.name, //一级标题
						desc: '¥' + orderInfo.salesPrice, //二级标题
						url: '/pages/order/order-detail/index?id=' + id, //消息跳转的url
						type: '订单', // 消息类型：商品、订单
					}
				});
			},
			goodsGet(id) {
				api.goodsGet(id).then(res => {
					let goodsSpu = res.data;
					let desc = '¥' + goodsSpu.priceDown;
					if (goodsSpu.priceUp && goodsSpu.priceDown != goodsSpu.priceUp) {
						desc = desc + ' - ¥' + goodsSpu.priceUp;
					}
					this.topMsgContent = { // JLIM自定义消息内容的长度有限制，所以精简一些
						id: goodsSpu.id, //ID
						imgUrl: goodsSpu.picUrls ? goodsSpu.picUrls[0] : '', //图片
						name: goodsSpu.name, //一级标题
						desc: desc, //二级标题
						url: '/pages/goods/goods-detail/index?id=' + id, //消息跳转的url
						type: '商品', // 消息类型：商品、订单
					}
				});
			},
			sendTopMsg() { // 发送顶部的消息详情
				if (!this.topMsgContent) return;
				if (!this.sendMsgSuccess) {
					//消息正在发送中
					uni.showToast({
						title: '消息正在发送中,请稍后...',
						icon: 'none'
					})
					return
				}
				this.sendMsgSuccess = false
				let JIM = app.globalData.JIM;
				let that = this;
				//自定义消息：https://doc.rentsoft.cn/#/js_v2/sdk_integrate/message?id=createcustommessage
				const options = {
					data: JSON.stringify(this.topMsgContent),
					extension: "",
					description: ""
				}
				JIM.createCustomMessage(options).then(({
					data
				}) => {
					let message = {
						recvID: this.getMessageOptions.userID,
						groupID: this.getMessageOptions.groupID,
						offlinePushInfo: '', //离线推送配置
						message: data,
					};
					this.sendMessage(message);
					this.topMsgContent = null
				}).catch(err => {
					console.log('创建自定义消息失败');
				})
			},
			to_send() {
				var that = this;
				var inputMsgText = that.inputMsgText
				if (!inputMsgText || inputMsgText == '') {
					//无内容直接跳出
					return;
				}
				if (!this.sendMsgSuccess) {
					//消息正在发送中
					uni.showToast({
						title: '消息正在发送中,请稍后...',
						icon: 'none'
					})
					return
				}
				this.sendMsgSuccess = false
				let JIM = app.globalData.JIM;
				JIM.createTextMessage(inputMsgText).then(({
					data
				}) => {
					let message = {
						recvID: this.getMessageOptions.userID,
						groupID: this.getMessageOptions.groupID,
						offlinePushInfo: '', //离线推送配置
						message: data,
					};
					this.sendMessage(message)

				}).catch(err => {
					uni.showToast({
						title: "创建消息失败",
						icon: "none"
					})
				})
			},
			loadChatRecord() { //获取聊天记录 https://doc.rentsoft.cn/#/js_v2/sdk_integrate/message?id=gethistorymessagelist

				if (!this.showPage) return
				uni.showLoading()
				let JIM = app.globalData.JIM;
				let that = this
				// 下方初始化聊天记录
				// 拉取本地的消息数据并保存
				JIM.getHistoryMessageList(this.getMessageOptions).then((res) => {
					const data = JSON.parse(res.data) || [];
					JimUtil.saveIMMsg(data)
					this.chatMessageRecord = data
					this.toBottom();
				}).catch(err => {
					//读取本地消息
					this.loadLocalChatRecord()
				});
				this.markMsgRead() //设置消息已读，更新会话未读数数据
				uni.hideLoading();
			},
			loadLocalChatRecord() { //读取本地消息
				if (!this.showPage) return
				// 取出保存的聊天数据
				let localMsgStr = uni.getStorageSync(this.chatRecordLocalSaveKey) // 本地消息
				const data = JSON.parse(localMsgStr) || [];
				this.chatMessageRecord = data
				this.toBottom();
			},
			toBottom() { //滑动到页面最下面
				let that = this
				setTimeout(function() {
					if (that.showPage) {
						uni.pageScrollTo({
							scrollTop: 9999999
						})
					}
				}, 1000);

			},
			markMsgRead() { //设置消息已读，更新会话未读数数据 https://doc.rentsoft.cn/#/js_v2/sdk_integrate/message?id=markc2cmessageasread
				const options = {
					userID: this.chatUserId,
					msgIDList: []
				}
				app.globalData.JIM.markC2CMessageAsRead(options).then((r) => {

				}).catch(err => {

				})
			},
			//编辑框事件
			InputFocus(e) {
				// APP底部有虚拟导航栏，需要动态计算一下高度
				let sysInfo = uni.getSystemInfoSync()
				let heightDiff = sysInfo.screenHeight - sysInfo.windowHeight
				let diff = e.detail.height - heightDiff
				this.InputBottom = diff > 0 ? diff : 0
			},
			InputBlur(e) {
				this.InputBottom = 0
			},
		}
	};
</script>
<style>
	.goods-bg {
		width: 94%;
		border-radius: 10rpx;
		margin: auto;
	}

	.image-box {
		margin: auto;
		width: 180rpx;
		height: 180rpx;
	}

	.message {
		margin-bottom: 100rpx !important;
		padding-bottom: 100rpx;
	}

	.message-bg {
		border-radius: 10rpx !important;
		word-break: break-all;
		word-wrap: break-word;
	}
</style>
